import { constantRoutes } from '@/router'
import Layout from '@/layout'
import { deepClone } from '@/utils'

import routerMap from '@/router/settings'

export function parseRouter(routers) {
  let routersData = deepClone(routers) || []
  routersData = routersData.map(routerItem => {
    routerItem.component = Layout
    if (!routerItem.children) {
      routerItem.children = []
    }
    routerItem.children = parseRouter_(routerItem.children)
    return routerItem
  })
  routersData.push({ path: '*', redirect: '/404', hidden: true })
  return routersData
}

function parseRouter_(routers) {
  return routers.map(routerItem => {
    routerItem.component = routerMap[routerItem.component]
    if (!routerItem.children) {
      routerItem.children = undefined
    } else {
      routerItem.children = parseRouter_(routerItem.children)
    }
    return routerItem
  })
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, routers) {
    return new Promise(resolve => {
      const accessedRoutes = parseRouter(routers)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
